import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken} from '@/utils/auth'
import cript from '@/utils/encript.js'
import {clientname, build} from '@/settings';
import router from '@/router'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: '/api',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is snt
    if (store.getters.token) {
      config.headers['Authorization'] = 'token ' + getToken()
    }
    config.headers["build"] = build
	  config.headers["version"] = '1.0.1'
    // console.log('-----------request', config)
    if(config.noEncript){
      return config
    }else{
      return cript.encript(config)
    }
    
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
var flag = 0
// res interceptor
service.interceptors.response.use(
  res => {
    flag = 0
    // 解密
    res = cript.decript(res)
    // 限制只有lessee==1的时候才允许打印日志
    if(store.getters.role=='admin' || localStorage.getItem('changeLesseeStatus')=='Y'){
      console.log('\n\n-----received request ' + res.config.method + ' ' + res.config.url)
      console.log('res:', res)
      console.log('-----end---------------------\n\n')
    }
   
    
    // if the custom code is not 20000, it is judged as an error.
    if(res.data.code == 8888){
      Message({
        message: res.data.message,
        duration: 5 * 1000
      })
    }
    return res
  },
  error => {
    console.log('err---' + flag, error) // for debug
    if(error.message.indexOf('401') != -1){
      if(flag == 0){
        store.commit('SET_TOKEN', '')
        store.commit('SET_ROLES', [])
        store.commit('SET_PERMISSIONS', [])
        removeToken()
        router.push(`/login`)
        flag = 1
      }
    }else{
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
